"""
@File    :   no_introduction.py
@Time    :   2024/03/28 22:22:57
@Author  :   Qrj
@Email   :   923207736@qq.com
@description   :   无需引入其他依赖的全局依赖
"""
from typing import AsyncGenerator

from fastapi import Request
from redis.asyncio import Redis
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import Session

from src.config import Settings, get_app_settings
from src.models.database import masterSessionLocal
from src.schemas.validate import (
    OrderBySearchValidateSchema,
    PaginationSearchValidateSchema,
)


async def depend_get_master_db_session() -> (
    AsyncGenerator[AsyncSession | Session, None]
):
    """sql数据库操作会话依赖

    Returns:
        AsyncGenerator[AsyncSession | Session, None]: 异步生成器

    Yields:
        Iterator[AsyncGenerator[AsyncSession]]: 操作会话
    """
    session = masterSessionLocal()
    try:
        yield session
    finally:
        await session.close()


def depend_get_token_redis_pool(request: Request) -> Redis:
    """获取token的redis连接池

    Args:
        request (Request): 请求对象

    Returns:
        Redis: token的redis连接池
    """
    return request.app.state.redis_token


def depend_get_cache_redis_pool(request: Request) -> Redis:
    """获取cache的redis连接池

    Args:
        request (Request): 请求对象

    Returns:
        Redis: cache的redis连接池
    """
    return request.app.state.redis_cache


def depend_get_app_settings() -> Settings:
    """获取应用配置

    Returns:
        Settings: 应用配置
    """
    return get_app_settings()


def depend_get_client_host(request: Request) -> str:
    """获取请求端的主机名或IP地址

    Args:
        request (Request): 请求对象

    Returns:
        str: 主机名或IP地址
    """
    return request.client.host


class PaginationDependencies:
    """分页的依赖类"""

    @staticmethod
    async def from_body(
        pagination: PaginationSearchValidateSchema,
    ) -> PaginationSearchValidateSchema:
        return pagination


class OrderByDependencies:
    """查询排序的依赖类"""

    @staticmethod
    async def from_body(
        order: OrderBySearchValidateSchema,
    ) -> OrderBySearchValidateSchema:
        return order
